package com.example.myys.ui.page

import android.app.Activity
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationRail
import androidx.compose.material3.NavigationRailItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.windowsizeclass.WindowSizeClass
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navigation
import com.example.myys.R
import com.example.myys.common.BottomItemData
import com.example.myys.ui.page.mhPage.Mh
import com.example.myys.ui.page.mhPage.MhReaderPage
import com.example.myys.ui.page.mhPage.PagesMh
import com.example.myys.ui.page.settingPage.Setting
import com.example.myys.ui.page.syPage.Sy
import com.example.myys.ui.page.webPage.WebIndex
import com.example.myys.ui.page.xsPage.PagesXs
import com.example.myys.ui.page.xsPage.ReaderPage
import com.example.myys.ui.page.xsPage.Xs
import com.example.myys.ui.page.ysPage.PagesYs
import com.example.myys.ui.page.ysPage.Ys
import com.example.myys.ui.page.ysPage.YsViedoPlay
import com.example.myys.ui.page.yyPage.Yy

//页面的枚举类
object Pages {
    const val PAGE_SY = "Sy" //首页
    const val PAGE_YS = "Ys" //影视
    const val PAGE_XS="Xs"   //小说
    const val PAGE_MH="Mh"   //漫画
    const val PAGE_YY="Yy"   //音乐
    const val PAGE_SETTING = "Setting" //设置
}
//app导航页
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun MyApp(windowSize: WindowSizeClass,activity: Activity) {
    //导航
    val navController = rememberNavController()
    //页面路由
    val menuData = listOf(
        BottomItemData(Pages.PAGE_SY, "首页", R.drawable.sy_tb),
        BottomItemData(Pages.PAGE_YS, "影视", R.drawable.ys_tb),
        BottomItemData(Pages.PAGE_XS, "小说", R.drawable.xs_tb),
        BottomItemData(Pages.PAGE_MH, "漫画", R.drawable.dm_tb),
        BottomItemData(Pages.PAGE_YY, "音乐", R.drawable.yy_tb),
        BottomItemData(Pages.PAGE_SETTING, "设置", R.drawable.dy_tb)
    )
    //将底部栏菜单数据的路由名整成一个list
    val routes = menuData.map { it.route }
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentDestination = navBackStackEntry?.destination

    val context = LocalContext.current


    when (windowSize.widthSizeClass) {
        WindowWidthSizeClass.Compact,WindowWidthSizeClass.Medium-> {
            //竖屏导航
            Scaffold(modifier = Modifier.fillMaxSize(), bottomBar = {
                //是否匹配导航显示导航栏
                if (currentDestination?.hierarchy?.any { routes.contains(it.route) } == true) {
                    NavigationBar() {
                        menuData.forEachIndexed { index, bottomItemData ->
                            NavigationBarItem(
                                //设置当前项是否为选中
                                selected = currentDestination.hierarchy.any {
                                    it.route?.contains(
                                        bottomItemData.route
                                    ) == true
                                },
                                icon = {
                                    Icon(
                                        modifier = Modifier.size(28.dp),
                                        painter = painterResource(id = bottomItemData.icon),
                                        contentDescription = "点击按钮"
                                    )
                                },
                                label = {
                                    Text(
                                        text = (bottomItemData.label)
                                    )
                                },
                                onClick = {
                                    navController.navigate(bottomItemData.route) {
                                        //使用此方法,可以避免生成一个重复的路由堆栈
                                        popUpTo(navController.graph.findStartDestination().id) {
                                            saveState = true
                                        }
                                        //避免重复选择会创建一个新的页面副本
                                        launchSingleTop = true
                                        // Restore state when reselecting a previously selected item
                                        //当重新选择之前已选择项目恢复页面状态
                                        restoreState = true
                                    }
                                },
                            )
                        }
                    }
                }
            }
            ) { innerPadding ->
                Surface(modifier = Modifier.padding(innerPadding)) {
                    mainNavHost(
                        navController = navController,
                        activity,
                    )
                }
            }
        }

        WindowWidthSizeClass.Expanded -> {
            //横屏导航
            Scaffold(modifier = Modifier.fillMaxSize()){innerPadding->
                Surface(modifier = Modifier.padding(innerPadding)) {
                    Row {
                        if (currentDestination?.hierarchy?.any { routes.contains(it.route) } == true) {
                            NavigationRail(
                                modifier = Modifier.padding(start = 8.dp, end = 8.dp),
                            ) {
                                Column(
                                    modifier = Modifier.fillMaxHeight(),
                                    verticalArrangement = Arrangement.Center,
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    menuData.forEachIndexed { index, bottomItemData ->
                                        NavigationRailItem(
                                            //设置当前项是否为选中
                                            selected = currentDestination.hierarchy.any {
                                                it.route?.contains(
                                                    bottomItemData.route
                                                ) == true
                                            },
                                            icon = {
                                                Icon(
                                                    modifier = Modifier.size(28.dp),
                                                    painter = painterResource(bottomItemData.icon),
                                                    contentDescription = "点击按钮"
                                                )
                                            },
                                            label = {
                                                Text(
                                                    text = (bottomItemData.label)
                                                )
                                            },
                                            onClick = {
                                                navController.navigate(bottomItemData.route) {
                                                    //使用此方法,可以避免生成一个重复的路由堆栈
                                                    popUpTo(navController.graph.findStartDestination().id) {
                                                        saveState = true
                                                    }
                                                    //避免重复选择会创建一个新的页面副本
                                                    launchSingleTop = true
                                                    // Restore state when reselecting a previously selected item
                                                    //当重新选择之前已选择项目恢复页面状态
                                                    restoreState = true
                                                }
                                            },
                                        )
                                        Spacer(modifier = Modifier.height(8.dp))
                                    }

                                }
                            }
                        }
                        //主路由
                        mainNavHost(
                            navController = navController,
                            activity,
                        )
                    }
                }
            }
        }
    }

    //两次退出返回
    val onBackPressedDispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher
    val lastBackPressedTime = remember { mutableStateOf(0L) }

    DisposableEffect(Unit) {
        val onBackPressedCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (navController.graph.startDestinationRoute == navController.currentDestination?.route) {
                    if (System.currentTimeMillis() - lastBackPressedTime.value < 2000) {
                        // 两次返回键在2秒内，退出应用
                        isEnabled = false
                        onBackPressedDispatcher?.onBackPressed() ?: activity.finishAndRemoveTask()
                        //activity.finishAndRemoveTask()
                    } else {
                        // 显示退出提示或执行其他操作
                        lastBackPressedTime.value = System.currentTimeMillis()
                        Toast.makeText(context, "再按一次退出", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    // 如果不是在根导航，则返回上一个目的地
                    navController.navigateUp()
                }
            }
        }
        onBackPressedDispatcher?.addCallback(onBackPressedCallback)
        onDispose {
            onBackPressedCallback.remove()
        }
    }
}
//app主页面路由
@Composable
fun mainNavHost(
    navController: NavHostController,
    activity: Activity,
) {
    //主路由
    NavHost(navController = navController, startDestination = Pages.PAGE_SY) {
        composable(Pages.PAGE_SY) {
            Sy(modifier = Modifier
            )
        }
        //YsMainComposable(navController)
        composable(Pages.PAGE_YS){
            Ys(navController, modifier = Modifier)
        }
        //小说首页
        composable(Pages.PAGE_XS){
            Xs(navController, modifier = Modifier)
        }
        composable(Pages.PAGE_MH){
            Mh(navController, modifier = Modifier
            )
        }
        composable(Pages.PAGE_YY){
            Yy(navController, modifier = Modifier
            )
        }
        composable(Pages.PAGE_SETTING) {
            Setting(modifier = Modifier
            )
        }
        //小说内容页
        composable("${PagesXs.SJNR}?url={url}&dataId={dataId}"){
            val url= it.arguments?.getString("url")
            val dataId=it.arguments?.getString("dataId")
            ReaderPage(url = url, dataId = dataId)
        }
        //漫画内容页
        composable("${PagesMh.MHNR}?url={url}&dataId={dataId}") {
            val url = it.arguments?.getString("url")
            val dataId = it.arguments?.getString("dataId")
            MhReaderPage(url = url, dataId = dataId)
        }
        //影视播放页
        composable("${PagesYs.VIDEOPLAY}?data={data}"){
            val dataBean= it.arguments?.getString("data")
            if (dataBean != null) {
                //VideoPlayScreen(onBackClick = { navController.popBackStack() },dataBean, activity = activity)
                YsViedoPlay(onBackClick = { navController.popBackStack() }, dataBean, activity)
            }
        }
        //webUi页面
        composable("webView?url={url}") {
            val url = it.arguments?.getString("url")
            if (url != null) {
                WebIndex(url)
            }
        }
    }
}


fun NavGraphBuilder.YsMainComposable(navController: NavHostController) {
    navigation(startDestination = "home", route = Pages.PAGE_YS) {
        composable("home") {
            Ys(navController, modifier = Modifier)
        }
    }
}



